﻿using Enter.Utils.EnumExt;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Linq;

namespace Enter.Utils.JsonExt
{
    public class EnumConverter : StringEnumConverter
    {
        private string EnumName { get; set; } = string.Empty;
        public EnumConverter()
        {
        }
        public EnumConverter(string enumName)
        {
            EnumName = enumName;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {

            if (value == null || value.ToString() == "0" || string.IsNullOrWhiteSpace(value.ToString()))
            {
                writer.WriteValue(string.Empty);
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(EnumName))
                {
                    EnumExtend.EnumMap.TryGetValue(EnumName, out var listItems);
                    if (listItems != null)
                    {
                        var item = listItems.Where(t => t.Value == value.ToString()).FirstOrDefault();
                        if (item != null)
                        {
                            writer.WriteValue(item.Text);
                        }
                        return;
                    }
                    writer.WriteValue(string.Empty);
                    return;
                }
                base.WriteJson(writer, value, serializer);
            }
        }
    }
}
